
Ext.ux.Filters = function(config){
	this.deferredUpdate = new Ext.util.DelayedTask(this.reload, this);
	//delete config.fields;
	Ext.apply(this, config);
};

Ext.extend(Ext.ux.Filters, Ext.util.Observable, {

	updateBuffer: 100,

	init: function(grid){
		//grid instanceof Ext.PagingToolbar
		if(grid instanceof Ext.grid.GridPanel){
			this.grid  = grid;
			this.store = this.grid.getStore();

			this.grid.filters = this;
			this.grid.addEvents({"filterupdate": true});
			grid.on("render", this.onRender, this);
		}else{

		}
	},

	onRender: function(){

		var hmenu;
		
		hmenu		= this.grid.getView().hmenu;
			
		this.sep	= hmenu.addSeparator();
		this.menus	= {};
		this.params	= {};

		var params	= this.params;
		var _timer	= setTimeout(Ext.emptyFn, 10);
		var checkHandler	= function(el){
			var sp	= el.value.split("\n");
			params[sp[0]]	= sp[1];
			this.deferredUpdate.cancel();
			this.deferredUpdate.delay(this.updateBuffer);
		}

		for(var i in this.fields){
			var items	= [{
				checked: true,
				text:'不选择',
				group: i + 'theme',
				scope: this,
				checkHandler: checkHandler,
				value: i + "\n" + '0'
			}];
			for(var j in this.fields[i]){
				if( this.fields[i][j]['id'] ){
					items.push({ //new Ext.menu.Item(
						checked: false,
						group: i + 'theme',
						text:  this.fields[i][j][i],
						scope: this,
						checkHandler: checkHandler,
						value: i + "\n" + this.fields[i][j]['id']
					});
				}
			}
			this.menus[i]	= hmenu.add(new Ext.menu.Item({
					text: '过滤',
					checkHandler: function (el){
						alert(this.text)
					},
					menu: new Ext.menu.Menu({
						items:	items
					})
			}));
		}

		hmenu.on('beforeshow', this.onMenu, this);
		//this.grid.getView().on("refresh", this.onRefresh, this);
		//this.updateColumnHeadings(this.grid.getView());
	},


	onMenu: function(filterMenu){
		/*
		var filter = this.getMenuFilter();
		if(filter){
			this.menu.menu = filter.menu;
			this.menu.setChecked(filter.active, false);
		}
		*/
		var key	= this.getMenuKey();
		if( this.menus[key] ){
			this.menus[key].setVisible(true);
			this.sep.setVisible(true);
		}else{
			//this.menu.setVisible(false);
			this.sep.setVisible(false);
		}
	},
	
	getMenuKey: function(){
		var view = this.grid.getView();
		if(!view || view.hdCtxIndex === undefined) return null;

		for(var i in this.menus){
			this.menus[i].setVisible(false);
		}

		return view.cm.config[view.hdCtxIndex].dataIndex;
	},


	reload: function(){
		this.deferredUpdate.cancel();
		this.store.baseParams.filter	= Ext.encode(this.params);
		this.store.reload();
	}
});